package com.szrt.socket.ch02.tcp.demo02;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

import org.junit.Test;

public class T3 {
	
	
	/**
	 * 服务端
	 * @throws Exception
	 */
	@Test
	public void server() throws Exception {
		
		while(true){
			
		
		ServerSocket ss=new ServerSocket(9998);
		
		Socket accept = ss.accept();
		
		//输入流
		InputStream is = accept.getInputStream();
		InputStreamReader isr = new InputStreamReader(is);
		
		//打印输入流的信息
		char[] b=new char[10];
		int len;
		while((len=isr.read(b))!=-1){
			String st=new String(b,0,len);
			System.out.println(st);
			
		}
		
		//给客户端发送反馈信息
		OutputStream os = accept.getOutputStream();
		
		Scanner sc=new Scanner(System.in);
		System.out.println("输入你的消息：");
		String nt = sc.next();
		
		if(nt.equals("eixt")){
			break;
		}
		
		os.write("爸爸：".getBytes());
		os.write(nt.getBytes());
		
		
		os.close();
		is.close();
		isr.close();
		accept.close();
		ss.close();
		sc.close();
		}
	}
	
	@Test
	public void client() throws IOException{
		
		while(true){
		Socket socket = new Socket(InetAddress.getByName("127.0.0.1"),9998);
		
		//得到输出流
		OutputStream os = socket.getOutputStream();
		
			
		
		Scanner sc=new Scanner(System.in);
		System.out.println("输入你的消息：");
		String nt = sc.next();
		
		if(nt.equals("eixt")){
			break;
		}
		os.write("儿子：".getBytes());
		os.write(nt.getBytes());
		
		//告诉服务器输出完毕
		socket.shutdownOutput();
		//4 接收到服务端发送过来的数据
		InputStream is=socket.getInputStream();
		
		InputStreamReader isr = new InputStreamReader(is);
		
		char[] b=new char[10];
		int len;
		while((len=isr.read(b))!=-1){
			String st=new String(b,0,len);
			System.out.println(st);
			
		}
		
		
	    is.close();
		isr.close();
		os.close();
		socket.close();
//		sc.close();
		
		}
		
		
	}

}
